from django.shortcuts import render
from django.views.generic import TemplateView

from commodity.models import Types, CommodityInfos


# Create your views here.
def indexView(request):
    title="首页"
    classContent=""
    commodityInfos=CommodityInfos.objects.order_by("-sold").all()[:8]
    types=Types.objects.all()#获取所有商品
    #筛选儿童服饰下的二级分类
    c1=[x.seconds for x in types if x.firsts=='儿童服饰']
    #获取儿童服饰分类下销量5最高
    clothes=CommodityInfos.objects.filter(types__in=c1).order_by('-sold')[:5]
    #筛选奶粉辅食下的二级分类
    f1=[x.seconds for x in types if x.firsts=='奶粉辅食']
    #获取奶粉辅食销量5最高
    food=CommodityInfos.objects.filter(types__in=f1).order_by('-sold')[:5]
    #筛选儿童用品分类下的二级分类
    g1=[x.seconds for x in types if x.firsts=='宝宝用品']
    #获取儿童用品销量5最高
    goods=CommodityInfos.objects.filter(types__in=g1).order_by('-sold')[:5]
    #所有变量传给模版进行渲染
    return render(request,'index.html',locals())

class indexClassView(TemplateView):
    #指定渲染模版
    template_name="index.html"
    template_engine=None
    content_type=None
    #额外的模版上下文的变量
    extra_context={'title':'首页','classContent':''}
    #重写获取上下文数据的方法
    def get_context_data(self, **kwargs):
        #获取父类的上下文
        context=super(indexClassView,self).get_context_data(**kwargs)
        #获取销量最高的8个商品
        context['commodityInfos']=CommodityInfos.objects.order_by("-sold").all()[:8]
        #获取所有商品分类
        types=Types.objects.all()
        #筛选商品
        cl=[x.seconds for x in types if x.firsts=='儿童服饰']
        context['clothes']=CommodityInfos.objects.filter(types__in=cl).order_by('-sold')[:5]
        fl=[x.seconds for x in types if x.firsts=='奶粉辅食']
        context['foods'] = CommodityInfos.objects.filter(types__in=fl).order_by('-sold')[:5]
        gl=[x.seconds for x in types if x.firsts=='儿童用品']
        context['goods'] = CommodityInfos.objects.filter(types__in=gl).order_by('-sold')[:5]
        return context

    def get(self,request,*args,**kwargs):
         #处理HTTP GET请求
         #获取上下文数据
        context=self.get_context_data(**kwargs)
         #渲染模版并返回响应
        return self.render_to_response(context)

    def post(self,request,*args,**kwargs):
        content=self.get_context_data(**kwargs)
        return self.render_to_response(content)

def page_not_found(request,exception):
        return render(request,'404.html',status=404)

def page_error(request):
        return render(request,'404.html',status=500)


